package cn.foolishbird.crow.encrypt;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;

/**
 * @author foolish-bird
 */
public final class AESUtils {

    /**
     * AES加密名
     */
    private static final String AES = "AES";

    private AESUtils() {

    }

    /**
     * aes加密
     *
     * @param content
     * @return
     */
    public static byte[] aesEncrypt(byte[] content, byte[] key, String model) throws Exception {
        check(content, key);
        if (StringUtils.isBlank(model)) {
            throw new IllegalArgumentException("AES模式不能为空");
        }

        SecretKeySpec keySpec = new SecretKeySpec(key, AES);
        Cipher cipher = Cipher.getInstance(model);
        cipher.init(ENCRYPT_MODE, keySpec);
        return cipher.doFinal(content);
    }


    /**
     * aes解密
     *
     * @param secret
     * @return
     */
    public static byte[] aesDecrypt(byte[] secret, byte[] key, String model) throws Exception {
        check(secret, key);
        if (StringUtils.isBlank(model)) {
            throw new IllegalArgumentException("AES模式不能为空");
        }

        SecretKeySpec keySpec = new SecretKeySpec(key, AES);
        Cipher cipher = Cipher.getInstance(model);
        cipher.init(DECRYPT_MODE, keySpec);
        return cipher.doFinal(secret);
    }


    /**
     * 随机生成秘钥
     *
     */
    /**
     * @param len 密钥长度 128, 192，256
     */
    public static byte[] aesKey(int len) throws NoSuchAlgorithmException {
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(len);
        //要生成多少位，只需要修改这里即可128, 192或256
        javax.crypto.SecretKey sk = kg.generateKey();
        return sk.getEncoded();
    }

    /**
     * 校验
     *
     * @param content
     * @param key
     */
    private static void check(byte[] content, byte[] key) {
        if (Objects.isNull(content) || content.length < 1) {
            throw new IllegalArgumentException("内容不能为空");
        }
        if (Objects.isNull(key) || key.length < 1) {
            throw new IllegalArgumentException("密钥不能为空");
        }
    }

}
